import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Socket Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SocketPage(),
    );
  }
}

class SocketPage extends StatefulWidget {
  @override
  _SocketPageState createState() => _SocketPageState();
}

class _SocketPageState extends State<SocketPage> {
  late ServerSocket _serverSocket;
  late Socket _clientSocket;
  late StreamSubscription<Socket> _subscription;
  List<String> _messages = [];

  @override
  void initState() {
    super.initState();
    _startServer();
  }

  @override
  void dispose() {
    _subscription.cancel();
    _serverSocket.close();
    super.dispose();
  }

  Future<void> _startServer() async {
    _serverSocket = await ServerSocket.bind('localhost', 12345);
    _subscription = _serverSocket.listen((clientSocket) {
      _clientSocket = clientSocket;
      _clientSocket.listen(
            (data) {
          setState(() {
            _messages.add(String.fromCharCodes(data).trim());
          });
        },
        onDone: () {
          _clientSocket.close();
        },
        onError: (e) {
          print('Socket error: $e');
        },
      );
    });
  }

  void _sendMessage(String message) {
    if (_clientSocket != null) {
      _clientSocket.write(message);
      setState(() {
        _messages.add('Sent: $message');
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Socket Demo'),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: ListView.builder(
              itemCount: _messages.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(_messages[index]),
                );
              },
            ),
          ),
          Divider(),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16),
            child: TextField(
              onSubmitted: (value) {
                _sendMessage(value);
              },
              decoration: InputDecoration(
                labelText: 'Message',
                suffixIcon: IconButton(
                  icon: Icon(Icons.send),
                  onPressed: () {
                    _sendMessage('Hello from Flutter');
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
